package com.etogc.groupchat.app;

import android.app.ActivityManager;
import android.content.Context;
import android.net.Uri;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.etogc.groupchat.common.CommonSp;
import com.etogc.groupchat.main.MainBiz;
import com.etogc.http.ReqDataHandler;
import com.etogc.http.ReqErrorHandler;
import com.etogc.http.VolleyHttpUtil;
import com.etogc.thirdsdk.rong.AddIPluginModule;
import com.etogc.util.ImageUtils;
import com.etogc.util.SpUtil;
import com.etogc.util.YcToastHelper;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.push.RongPushClient;

/**
 * Application
 * Created by ZeroVoid on 2018-1-30.
 */

public class App extends MultiDexApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        initToastHelper();
        initVolleyV3Helper();
        initSp();
        initRong();
        initUmeng();
    }

    private void initVolleyV3Helper() {
        VolleyHttpUtil.getInstance().setServerURL("http://www.baidu.com");
        VolleyHttpUtil.getInstance().initVolleyHttpUtil(getApplicationContext());
        VolleyHttpUtil.getInstance().setDebug(true);
    }


    private void initToastHelper() {
        YcToastHelper.getInstance().init(getApplicationContext());
    }

    private void initSp() {
        SpUtil.getInstance().init(getApplicationContext());
    }


    private void initUmeng() {
        UMConfigure.init(this, "5aa56224a40fa360680006f0", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        UMShareAPI.get(this);
        UMConfigure.setLogEnabled(true);
        PlatformConfig.setWeixin("wx3b7b08cc1a323937", "fb6992ba4ea32d398f4699999a025153");
    }

    //初始化RONG IM组件
    private void initRong() {

        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {
            RongIM.init(this);
            RongIM.setConnectionStatusListener(new YcConnectionStatusListener(this));
//            RongIM.registerMessageTemplate(new RealTimeLocationMessageProvider());
            //id=123 name=123
            RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
                @Override
                public boolean onReceived(Message message, int i) {
                    return !CommonSp.canRecvMessage();
                }
            });
            getUserInfo();
            RongPushClient.init(this, "ik1qhw09ip2ep");
            RongPushClient.registerHWPush(this);
        }

        //自定义面板
        try {
            List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules();
            if (moduleList != null) {
                IExtensionModule module = null;
                for (IExtensionModule extensionModule : moduleList) {
                    if (extensionModule instanceof DefaultExtensionModule) {
                        module = extensionModule;
                        break;
                    }
                }
                RongExtensionManager.getInstance().unregisterExtensionModule(module);//注销之前的
                RongExtensionManager.getInstance().registerExtensionModule(new AddIPluginModule());//注册新的
                List<IExtensionModule> moduleList2 = RongExtensionManager.getInstance().getExtensionModules();
                Log.i("app", "moduleList.size() = " + moduleList2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取融云用户信息
     */
    private void getUserInfo() {
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String s) {
                final UserInfo[] userInfo = new UserInfo[1];
                MainBiz.getUserInfo(s, new VolleyHttpUtil.ResponseCallBack() {
                    @Override
                    public void handleResponse(JSONObject response, int errCode) {
                        boolean isOk = ReqErrorHandler.getInstance().isSuccess(response, true);
                        Log.e("Biz", response.toString());
                        if (isOk) {
                            Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                            if (map != null) {
                                Map<String, Object> mapUser = (Map<String, Object>) map.get("user");
                                String nickName = String.valueOf(mapUser.get("nickname"));
                                String userID = String.valueOf(mapUser.get("id"));
                                String photo = ImageUtils.getImageUrl(String.valueOf(mapUser.get("photo")));
                                userInfo[0] = new UserInfo(userID, nickName, Uri.parse(photo));
                                RongIM.getInstance().refreshUserInfoCache(userInfo[0]);
                            }
                        }
                    }
                });
                return userInfo[0];
            }
        }, true);
        initMgrInfo();
    }

    //单独初始化100000的个人信息,因为服务端没有
    private void initMgrInfo() {
        String nickName = "系统消息";
        String userID = "100000";
        String photo = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527490397376&di=ac09d688310417e8753bc5c1feee92a2&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01af985927beeeb5b3086ed47f7e57.png%401280w_1l_2o_100sh.png";
        RongIM.getInstance().refreshUserInfoCache(new UserInfo(userID, nickName, Uri.parse(photo)));
    }

//    public static DisplayImageOptions getOptions() {
//        return options;
//    }

//    ic_private void initDisplayImageOptions() {
//        options = new DisplayImageOptions.Builder()
//                .showImageForEmptyUri(R.drawable.de_default_portrait)
//                .showImageOnFail(R.drawable.de_default_portrait)
//                .showImageOnLoading(R.drawable.de_default_portrait)
//                .displayer((BitmapDisplayer) new FadeInBitmapDisplayer(300))
//                .cacheInMemory(true)
//                .cacheOnDisk(true)
//                .build();
//    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }
}

//    ic_private void umeng4six() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
//            ActivityCompat.requestPermissions(this, mPermissionList, 123);
//        }
//
//    }

